/**
 * 
 */
package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.Soez6001Service;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;

/** 
 * 超商/郵局撥款統計查詢
 * @author Jeff Gu
 *
 */
public class Soez6001ActionBean extends BaseActionBean {

	@SpringBean("soez6001Service")
	private Soez6001Service soez6001Service;

	@SpringBean("groupService")
	private GroupService groupService;


	private static final String DEFAULT_JSP = "/WEB-INF/views/soez6001/soez6001.jsp";


	private static final String AJAX_LIST= "/WEB-INF/views/soez6001/soez6001List.jsp";

	private static final String AJAX_LIST_DETAIL = "/WEB-INF/views/soez6001/soez6001DetailList.jsp";

	/**
	 * 業者代號查詢畫面
	 */
	private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez6001/soez6001groupPopUpList.jsp";

	/**
	 * 查詢條件
	 * 撥款日期 資料期間起
	 */
	@Validate( converter=DateTypeConverter.class)
	private Date qryDateFrom;

	/**
	 * 查詢條件
	 * 撥款日期 資料期間迄
	 */
	@Validate( converter=DateTypeConverter.class)
	private Date qryDateTo;


	/**
	 * 查詢條件
	 * 帳單業者
	 */
	private Group qryGroup;


	private String queryChannel;
	
	
	   /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
  
	/**
	 * 查詢結果
	 */
	private PaginatedList<Map<String, Object>> queryResult;

	
	/**
	 * 區分需要觀察的明細類型,以便調整jsp form需要帶入的條件匯出跟查詢
	 *detailType =1.單通路單代碼 ex: 7-11  61D 
	 *detailType=2.單通路全代碼 ex: 7-11  全部代碼
	 *detailType=3.全通路全代碼 (畫面上的超商／郵局合計)ex: 7-11  okcvs
	 */
	private String detailType;

	
	
      
	@DontBind
	@DefaultHandler
	public Resolution doDefault()
	{
		logger.debug("Enter doDefault mehtod.");
		try {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			/* 初始化畫面查詢資料 */
			qryDateFrom=cal.getTime();
			qryDateTo=cal.getTime();
		}
		catch (Exception e) {
			logger.error("超商/郵局撥款統計查詢錯誤(Soez6001ActionBean.doDefault): {}",e);
		}
		return new ForwardResolution(DEFAULT_JSP); 
	}


	/**
	 * 查詢超商郵局已撥款資料
	 * @return
	 */
	public Resolution doAjaxQuery()
	{
		logger.debug("Enter doAjaxQuery mehtod.");
		try {

			
			Group	group=new Group();
			
			/* 畫面上有輸入卷商代號*/
			if(null!=qryGroup && StringUtils.isNotEmpty(qryGroup.getGroupNo())){
				group=qryGroup;
			}
			/* 限制卷商查詢 */
			if (!UserUtil.isBankGroup())
			{
				group=UserUtil.getUserGroup();
			}
			
			if (null == queryResult)
				queryResult = new PaginatedList<Map<String,Object>>();
			/* 單通路單代碼明細資料保持顯示全部不分頁*/
			queryResult.setPageSize(-1);

			String[] channels = {
					"D","E","F" ,"G", "H"};			
			queryResult = soez6001Service.queryTransferLogByGroup(group, channels, qryDateFrom, qryDateTo, queryResult);

		}
		catch (Exception e) {
			logger.error("超商/郵局撥款統計查詢錯誤(Soez6001ActionBean.doAjaxQuery): {}",e);
			// 轉換錯誤訊息
			ValidationErrors errors = new ValidationErrors();
			errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
			getContext().setValidationErrors(errors);
			// 回傳 錯誤 HTML fragments
			return super.errorsToHtmlStreams(errors);

		}
		return new ForwardResolution(AJAX_LIST); 
	}

	
	/**
	 * 
	 * 根據通路跟日期 取得  CommissionCode 明細 (可分群組)
	 * @author Jeff
	 */
	public Resolution doAjaxQueryTotalCommissionCode()
	{
		logger.debug("Enter doAjaxQueryTotalCommissionCode mehtod.");
		try {

			/* 不是帳單業者要加入限制 */
			Group	group=new Group();
			
			/* 畫面上有輸入卷商代號*/
			if(null!=qryGroup && StringUtils.isNotEmpty(qryGroup.getGroupNo())){
				group=qryGroup;
			}
			/* 限制卷商查詢 */
			if (!UserUtil.isBankGroup())
			{
				group=UserUtil.getUserGroup();
			}

			if (null == queryResult)
				queryResult = new PaginatedList<Map<String,Object>>();

			/**
			 * 區分需要觀察的明細類型,以便調整jsp form需要帶入的條件匯出跟查詢
			 *detailType=2.單通路全代碼 ex: 7-11  全部代碼
			 *detailType=3.全通路全代碼 (畫面上的超商／郵局合計)ex: 7-11  okcvs
			 */

			if("3".equals(detailType)){
				String[] channels = {
						"D","E","F" ,"G", "H"};	

				Date [] qryDateFroms = 
				{
						qryDateFrom,qryDateFrom,qryDateFrom,qryDateFrom,qryDateFrom
				};

				Date[] qryDateTos =
				{
						qryDateTo,qryDateTo,qryDateTo,qryDateTo,qryDateTo
				};

				queryResult = soez6001Service.queryGroupFeedbackLogByChannel(group,channels, qryDateFroms, qryDateTos,queryResult);
			}else if("2".equals(detailType)){

				String[] channels = {queryChannel};

				Date [] qryDateFroms = {qryDateFrom};

				Date[] qryDateTos ={qryDateTo};

				queryResult = soez6001Service.queryGroupFeedbackLogByChannel(group,channels, qryDateFroms, qryDateTos,queryResult);

			}



		}
		catch (Exception e) {
			logger.error("超商代收統計查詢錯誤(Soez6001ActionBean.doAjaxQueryTotalCommissionCode): {}",e);

			// 轉換錯誤訊息
			ValidationErrors errors = new ValidationErrors();
			errors.addGlobalError(new LocalizableError("doAjaxQueryTotalCommissionCode.exception") );
			getContext().setValidationErrors(errors);
			// 回傳 錯誤 HTML fragments
			return super.errorsToHtmlStreams(errors);

		}
		return new ForwardResolution(AJAX_LIST_DETAIL); 
	}
	
	
	
	

	/**
	 * 依通路與撥款日期查詢繳費單明細
	 * 
	 * @return
	 */
	public Resolution doAjaxQueryPayments()
	{
		logger.debug("Enter doAjaxQueryPayments mehtod.");
		try {

			/* 限制卷商查詢 */
			Group	group=new Group();
			if (!UserUtil.isBankGroup())
			{
				group=UserUtil.getUserGroup();
			}
			/*
			 * 區分需要觀察的明細類型,以便調整jsp form需要帶入的條件匯出跟查詢
			 *detailType=3.全通路全代碼 (畫面上的超商／郵局合計)ex: 7-11  okcvs
			 */
			String message = "";
			StreamingResolution resolution = new StreamingResolution("text/html", new StringReader(message.toString()));
			resolution.setCharacterEncoding("UTF-8");
			return resolution;

		}
		catch (Exception e) {
			logger.error("超商/郵局撥款統計查詢錯誤(Soez6001ActionBean.doAjaxQueryPayments): {}",e);
			// 轉換錯誤訊息
			ValidationErrors errors = new ValidationErrors();
			errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
			getContext().setValidationErrors(errors);
			// 回傳 錯誤 HTML fragments
			return super.errorsToHtmlStreams(errors);

		}

	}


	/**
	 * 下載超商郵局撥款統計表
	 * @return
	 */
	public Resolution doAjaxDownloadExcelFile()
	{
		logger.debug("Enter doAjaxDownloadExcelFile mehtod.");
		try {


			//如果不是銀行端，則查詢條件要加入帳單業者限制
			/* 限制卷商查詢 */
			Group	group=new Group();
			if (!UserUtil.isBankGroup())
			{
				group=UserUtil.getUserGroup();
			}
			//TODO
			String downloadFilePath = null ;

			if (null == downloadFilePath)
			{
				// 查無資料
			}

			File downloadFile = new File(downloadFilePath);
			byte[] bytes = new byte[(int)downloadFile.length()];

			BufferedInputStream bufferedInputStream = 
				new BufferedInputStream(new FileInputStream(downloadFile)); 

			bufferedInputStream.read(bytes);

			ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
			inputStream.close();
			bufferedInputStream.close();
			String isoFileName = new String("超商郵局撥款統計表.xls".getBytes("MS950"), "ISO8859-1");

			StreamingResolution streamingResolution = new StreamingResolution( 
					"application/vnd.ms-excel",inputStream).setFilename(isoFileName);

			return streamingResolution;
		}
		catch (Exception e) {
			logger.error("doAjaxDownloadExcelFile ", e);
		}
		return new ForwardResolution(DEFAULT_JSP); 
	}


	/**
	 * 下載超商郵局撥款統計明細表
	 * @return
	 */
	public Resolution doAjaxDownloadDetailExcel()
	{
		logger.debug("Enter doAjaxDownloadDetailExcel mehtod.");
		try {


			//如果不是銀行端，則查詢條件要加入帳單業者限制
			/* 限制卷商查詢 */
			Group	group=new Group();
			if (!UserUtil.isBankGroup())
			{
				group=UserUtil.getUserGroup();
			}
			//TODO
			String downloadFilePath = null ;

			if (null == downloadFilePath)
			{
				// 查無資料
			}

			File downloadFile = new File(downloadFilePath);
			byte[] bytes = new byte[(int)downloadFile.length()];

			BufferedInputStream bufferedInputStream = 
				new BufferedInputStream(new FileInputStream(downloadFile)); 

			bufferedInputStream.read(bytes);

			ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
			inputStream.close();
			bufferedInputStream.close();
			String isoFileName = new String("超商郵局撥款統計明細表.xls".getBytes("MS950"), "ISO8859-1");

			StreamingResolution streamingResolution = new StreamingResolution( 
					"application/vnd.ms-excel",inputStream).setFilename(isoFileName);

			return streamingResolution;
		}
		catch (Exception e) {
			logger.error("doAjaxDownloadDetailExcel ", e);
		}
		return new ForwardResolution(DEFAULT_JSP); 
	}




	/**
	 * 帳單業者查詢
	 * @return
	 */
	public Resolution doAjaxQueryGroups()
	{
		logger.debug("Enter doAjaxQueryGroups mehtod.");
		try {
			//如果不是銀行端，則查詢條件要加入帳單業者限制
			if (!UserUtil.isBankGroup())
			{
				throw new Exception("No Authority");
			}


			//USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
			if (null == qryGroup)
				qryGroup = new Group();

			//呼叫服務查詢
			queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
		}
		catch (Exception e) {
			logger.error("帳務處理統計表-帳單業者查詢錯誤(Soez5004ActionBean.doAjaxQueryGroups):", e);

			// 轉換錯誤訊息
			ValidationErrors errors = new ValidationErrors();
			errors.addGlobalError(new SimpleError("查詢錯誤！"));
			getContext().setValidationErrors(errors);
			// 回傳 錯誤 HTML fragments
			return super.errorsToHtmlStreams(errors);
		}

		return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
	}




	public Date getQryDateFrom() {
		return qryDateFrom;
	}

	public void setQryDateFrom(Date qryDateFrom) {
		this.qryDateFrom = qryDateFrom;
	}

	public Date getQryDateTo() {
		return qryDateTo;
	}

	public void setQryDateTo(Date qryDateTo) {
		this.qryDateTo = qryDateTo;
	}


	public Group getQryGroup() {
		return qryGroup;
	}


	public void setQryGroup(Group qryGroup) {
		this.qryGroup = qryGroup;
	}


	public PaginatedList<Group> getQueryGroupResult() {
		return queryGroupResult;
	}


	public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
		this.queryGroupResult = queryGroupResult;
	}


	public PaginatedList<Map<String, Object>> getQueryResult() {
		return queryResult;
	}


	public void setQueryResult(PaginatedList<Map<String, Object>> queryResult) {
		this.queryResult = queryResult;
	}







}
